// https://github.com/electron/i18n/tree/master/content/zh-CN/docs

const { app, BrowserWindow, dialog } = require('electron')
const path = require('path')
const url = require('url')
const fs = require('fs');

function getConfigFilePath() {
    const dir = path.join(app.getPath("appData"), "mygameengine");
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);

    }
    const configFilepath = path.join(dir, 'app.json');
    if (!fs.existsSync(configFilepath)) {
        fs.writeFileSync(configFilepath, '{}', 'utf-8');
    }
    return configFilepath;

}

function openEditorWindow(gameUrl) {
    // Create the browser window.
   
    win = new BrowserWindow({ width: 1600, height: 900 })
    const editorURL = "file://" + __dirname + "/editor/index.html?gameURL=" + encodeURIComponent(gameUrl);
   
    win.loadURL(editorURL)
    win.openDevTools();
}

function openSelectProjectWindow(callback) {
    dialog.showOpenDialog({
        title: "请选择一个游戏文件夹!",
        properties: ["openDirectory"]
    }, (dirs) => {
        if (!dirs) {
            dialog.showMessageBox({ message: "由于您没有选择文件夹，本游戏引擎即将关闭" })
            app.exit();
        }
        else {
            callback(dirs[0])
        }
    });
}

function onSelectProject(gameURL) {
    if (fs.existsSync(gameURL + "/map.json")) {
        const data = { gameUrl: gameURL };
        fs.writeFileSync(configFilepath, JSON.stringify(data, null, '\t', 'utf-8'));
        openEditorWindow(gameURL);  
        


    }
    else {
        dialog.showMessageBox({ message: "请选择一个游戏文件夹" })
        openSelectProjectWindow(onSelectProject)
    }
}

const configFilepath = getConfigFilePath();
 console.log(configFilepath);

function initEditor() {

   
    const content = fs.readFileSync(configFilepath, 'utf-8');
    const config = JSON.parse(content);
    

    const gameUrl = config.gameUrl;
   
    
    if (gameUrl) {
        
        openEditorWindow(gameUrl);

    }
    else {
        openSelectProjectWindow(onSelectProject);
    }
}

app.on('ready', initEditor)